package com.application.chiettinhdienluc.ui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.application.chiettinhdienluc.R;
import com.application.chiettinhdienluc.adapter.NhanCongInfoAdapter;
import com.application.chiettinhdienluc.app.MainApplication;
import com.application.chiettinhdienluc.data.GlobalData;
import com.application.chiettinhdienluc.db.NhanCongChiTietDataSource;
import com.application.chiettinhdienluc.model.NhanCongChiTietModel;
import com.application.chiettinhdienluc.utils.CalculationUtils;
import com.application.chiettinhdienluc.utils.Log;
import com.application.chiettinhdienluc.utils.Utils;

public class NhanCongInfoFragmentActivity extends FragmentActivity {
	
	public static class NhancongInfoFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<NhanCongChiTietModel>> {
		private final String TAG = NhancongInfoFragment.class.getSimpleName();
		private Resources res;
		private ListView lvNhancong;
		NhanCongInfoAdapter dataAdapter = null;
		ArrayList<NhanCongChiTietModel> listNhancongModel = new ArrayList<NhanCongChiTietModel>();
		private ProgressBar pro_loading_nhancong;
		private LinearLayout rlo_cpnc_summary;
		private boolean UpdateListenerIsRegistered = false;
		private UpdateListener listener = null;
		private TextView tv_cpnc_value;
		
		private EditText edt_filter_nhancong_info_list;
		private TextView tvfilter_nhancong_info_result_count;
		private TextWatcher textChangeListener = null;

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			getActivity().getWindow().setBackgroundDrawable(null);
		}

		/**
		 * The Fragment's UI
		 */
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View v = inflater.inflate(R.layout.nhancong_info, container, false);
			res = getResources();
			lvNhancong = (ListView) v.findViewById(R.id.lvNhancong);
			pro_loading_nhancong = (ProgressBar)v.findViewById(R.id.pro_loading_nhancong);
			rlo_cpnc_summary = (LinearLayout)v.findViewById(R.id.rlo_cpnc_summary);
			dataAdapter = new NhanCongInfoAdapter(getActivity(), listNhancongModel);
			lvNhancong.setAdapter(dataAdapter);
			
			tv_cpnc_value = (TextView)v.findViewById(R.id.tv_cpnc_value);
			tv_cpnc_value.setText(String.valueOf(CalculationUtils.calculateChiPhiNhanCong(listNhancongModel)));
					
			

			pro_loading_nhancong.setVisibility(View.VISIBLE);
			rlo_cpnc_summary.setVisibility(View.GONE);
			lvNhancong.setVisibility(View.GONE);
			
			tvfilter_nhancong_info_result_count = (TextView)v.findViewById(R.id.tvfilter_nhancong_info_result_count);
			edt_filter_nhancong_info_list = (EditText) v.findViewById(R.id.edt_filter_nhancong_info_list);
			textChangeListener = new TextWatcher() {
				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
					dataAdapter.getFilter().filter(s, new Filter.FilterListener() {
						@Override
						public void onFilterComplete(int count) {
							tvfilter_nhancong_info_result_count.setText(String.format(
									res.getString(R.string.str_filter_result_count),
									count));
						}
					});
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,
						int after) {
					// TODO Auto-generated method stub
				}

				@Override
				public void afterTextChanged(Editable s) {
					// TODO Auto-generated method stub
				}
			};
			
			edt_filter_nhancong_info_list.addTextChangedListener(textChangeListener);
			
			getLoaderManager().initLoader(0, null, this);
			
//			displayListView();
			return v;
		}	

		@Override
		public void onResume() {
			// TODO Auto-generated method stub
			super.onResume();
			
			if (!UpdateListenerIsRegistered && listener != null) {
				IntentFilter intentFilter = new IntentFilter();
				intentFilter.addAction("com.application.chiettinhdienluc.ui.RefreshNhanCongInfo");
				intentFilter.addAction("com.application.chiettinhdienluc.ui.SaveNhanCongInfo");
				intentFilter.addAction("com.application.chiettinhdienluc.ui.Selected_NhanCong_Change");
				
				getActivity().registerReceiver(listener, intentFilter);
				UpdateListenerIsRegistered = true;
			}

//			if (GlobalData.isDoneNhanCong) {
//				displayListView();
//				GlobalData.isDoneNhanCong=false;
//			}
		}   
		
		

//		private void displayListView() {
//
//			if (listNhancongModel != null)
//				listNhancongModel.clear();
//
//			NhanCongChiTietDataSource dbHelper = new NhanCongChiTietDataSource(getActivity().getApplicationContext());
//
//			listNhancongModel = dbHelper.getNhancongChiTietByHoSoId(1);
//
//			NhanCongChitietLoader loader = new NhanCongChitietLoader(dataAdapter, getActivity());
//			loader.execute();
//
//		}

		@Override
		public void onPause() {
			// TODO Auto-generated method stub
			try {
				if (UpdateListenerIsRegistered && listener != null) {
					getActivity().unregisterReceiver(listener);
					UpdateListenerIsRegistered = false;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			super.onPause();
		}

		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			listener = new UpdateListener();
		}

		@Override
		public Loader<List<NhanCongChiTietModel>> onCreateLoader(int arg0, Bundle arg1) {
			// TODO Auto-generated method stub
			return new AppListLoader(getActivity());
		}

		@Override
		public void onLoadFinished(Loader<List<NhanCongChiTietModel>> arg0, List<NhanCongChiTietModel> arg1) {
			// TODO Auto-generated method stub
			
			Collections.sort(arg1, new Comparator<NhanCongChiTietModel>(){
				  public int compare(NhanCongChiTietModel obj1, NhanCongChiTietModel obj2)
				  {
				    // TODO Auto-generated method stub
					  return (obj1.getOrder() < obj2.getOrder()) ? -1: (obj1.getOrder() > obj2.getOrder()) ? 1: (obj1.getTenCongviec().compareToIgnoreCase(obj2.getTenCongviec())) ;
				  }
				}); 
			
			dataAdapter.setItemList(arg1);
			dataAdapter.notifyDataSetChanged();
			
			double cpnc = CalculationUtils.calculateChiPhiNhanCong(arg1);
			tv_cpnc_value.setText(Utils.formatDoubleNumber(cpnc));
			GlobalData.ChiPhiNhanCong = cpnc;
			
			tvfilter_nhancong_info_result_count.setText(String.format(
					res.getString(R.string.str_filter_result_count),
					dataAdapter.getCount()));
			
			Intent i = new Intent();
//			i.setAction("com.application.chiettinhdienluc.ui.result_change");
			i.setAction("com.application.chiettinhdienluc.ui.UpdateLocalChietTinhModelResultInfo");
			i.putExtra("UpdateDataForResultTab", true);
			MainApplication.getAppContext().sendBroadcast(i);
			
			pro_loading_nhancong.setVisibility(View.GONE);
			rlo_cpnc_summary.setVisibility(View.VISIBLE);
			lvNhancong.setVisibility(View.VISIBLE);
		}

		@Override
		public void onLoaderReset(Loader<List<NhanCongChiTietModel>> arg0) {
			// TODO Auto-generated method stub
		}
		
		protected class UpdateListener extends BroadcastReceiver {
			@Override
			public void onReceive(Context context, Intent intent) {
				try {
					if(intent != null && !TextUtils.isEmpty(intent.getAction()))
					{
						String action = intent.getAction();
                        Log.i(TAG, intent.getAction());
						if(!TextUtils.isEmpty(action))							
						{
							if (intent.getAction().equalsIgnoreCase("com.application.chiettinhdienluc.ui.Selected_NhanCong_Change")) {
								
								double cpnc = CalculationUtils.calculateChiPhiNhanCong(GlobalData.SelectedNhanCongList);
								GlobalData.ChiPhiNhanCong = cpnc;
								tv_cpnc_value.setText(Utils.formatDoubleNumber(cpnc));
								
//								CalculationUtils.calculate(GlobalData.globalChietTinh, (long)GlobalData.ChiPhiVatTu, (long)GlobalData.ChiPhiNhanCong);
								
								Intent i = new Intent();
//								i.setAction("com.application.chiettinhdienluc.ui.result_change");
								i.setAction("com.application.chiettinhdienluc.ui.UpdateLocalChietTinhModelResultInfo");
								i.putExtra("UpdateDataForResultTab", true);
								MainApplication.getAppContext().sendBroadcast(i);
								//Log.i(TAG, String.valueOf(CalculationUtils.calculateChiPhiNhanCong(GlobalData.SelectedNhanCongList)));
								
							} 
							else if(action.equals("com.application.chiettinhdienluc.ui.RefreshNhanCongInfo"))
							{
//								updateDisplayInfoGlobal();
								getLoaderManager().restartLoader(0, null, NhancongInfoFragment.this);
								if(GlobalData.SelectedNhanCongList != null)  
									GlobalData.SelectedNhanCongList.clear();
								
							}else if(action.equals("com.application.chiettinhdienluc.ui.SaveNhanCongInfo"))	
							{
								NhanCongChiTietDataSource dbHelper = new NhanCongChiTietDataSource();
								
								for(int i = 0, n = dataAdapter.getCount(); i < n; i++)
								{
									NhanCongChiTietModel item = (NhanCongChiTietModel)dataAdapter.getItem(i);
									item.setMaDviQly(MainApplication.getMaDonViQuanLy());
									
									if(item.getKhoiLuong() > 0)
									{					
										long rowid = dbHelper.updateValue(item);
										
										Log.i(TAG, rowid + " ");
									}
									else
									{
										dbHelper.deleteItemWithQuantityZero(item, true);
									}
								}
								
								if(MainTabFragmentActivity.getInstance() != null)
								{
									MainTabFragmentActivity.getInstance().showHideProgressDialog(false);
									if(MainTabFragmentActivity.getInstance().isExitAfterSave())
									{
										MainTabFragmentActivity.getInstance().setExitAfterSave(false);
										MainTabFragmentActivity.getInstance().finishActivityResult();
									}
								}
//								if(MainApplication.getAppContext() != null)
//								{
//									Intent broadcastIntent = new Intent();
//									broadcastIntent.setAction("com.application.chiettinhdienluc.ui.SaveKhaoSatInfo");
//									MainApplication.getAppContext().sendBroadcast(broadcastIntent);
//								}
							}
						}	
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	


	
	public static class AppListLoader extends AsyncTaskLoader<List<NhanCongChiTietModel>> {

		List<NhanCongChiTietModel> mNhanCongChiTiets;

		public AppListLoader(Context context) {
			super(context);

			// Retrieve the package manager for later use; note we don't
			// use 'context' directly but instead the save global application
			// context returned by getContext().
		}

		@Override 
		public List<NhanCongChiTietModel> loadInBackground() {
			// Retrieve all known applications.
			// Create corresponding array of entries and load their labels.
			List<NhanCongChiTietModel> entries = new ArrayList<NhanCongChiTietModel>();

			NhanCongChiTietDataSource dbHelper = new NhanCongChiTietDataSource();

			entries = dbHelper.getNhancongChiTietByHoSoId(GlobalData.globalChietTinh.get_Id());
			
			GlobalData.nhancongInfoListInDB.clear();
			for(int i = 0, n = entries.size(); i < n; i++)
			{
				GlobalData.nhancongInfoListInDB.add(entries.get(i).getMaCongViec());
				
				if(GlobalData.SelectedNhanCongList != null && GlobalData.SelectedNhanCongList.contain(entries.get(i).getMaCongViec()))
				{
					NhanCongChiTietModel item = GlobalData.SelectedNhanCongList.get(entries.get(i).getMaCongViec());
					
					if(item != null)
					{
						entries.get(i).setKhoiLuong(item.getKhoiLuong());
						entries.get(i).setCheck(item.getKhoiLuong() > 0);
						
						if(entries.get(i).isCheck()) 
							entries.get(i).setOrder(0);
						else
							entries.get(i).setOrder(1);
					}
				}
			}
			
			Log.i("NhanCongChiTietModel number", entries.size() + " ");
			// Done!
			return entries;
		}

		/**
		 * Called when there is new data to deliver to the client.  The
		 * super class will take care of delivering it; the implementation
		 * here just adds a little more logic.
		 */
		@Override 
		public void deliverResult(List<NhanCongChiTietModel> datas) {
			if (isReset()) {
				// An async query came in while the loader is stopped.  We
				// don't need the result.
				if (datas != null) {
					onReleaseResources(datas);
				}
			}
			List<NhanCongChiTietModel> oldDatas = datas;
			mNhanCongChiTiets = datas;

			if (isStarted()) {
				super.deliverResult(datas);
			}

			if (oldDatas != null) {
				onReleaseResources(oldDatas);
			}
		}

		/**
		 * Handles a request to start the Loader.
		 */
		@Override 
		protected void onStartLoading() {
//			if (mVatTuChiTiets != null) {
//				// If we currently have a result available, deliver it
//				// immediately.
//				deliverResult(mVatTuChiTiets);
//			}

			//            if (takeContentChanged() || mVatTuChiTiets == null) {
			//                // If the data has changed since the last time it was loaded
			//                // or is not currently available, start a load.
			//                forceLoad();
			//            }
			forceLoad();
		}

		/**
		 * Handles a request to stop the Loader.
		 */
		@Override 
		protected void onStopLoading() {
			// Attempt to cancel the current load task if possible.
			cancelLoad();
		}

		/**
		 * Handles a request to cancel a load.
		 */
		@Override 
		public void onCanceled(List<NhanCongChiTietModel> datas) {
			super.onCanceled(datas);

			// At this point we can release the resources associated with 'apps'
			// if needed.
			onReleaseResources(datas);
		}

		/**
		 * Handles a request to completely reset the Loader.
		 */
		@Override protected void onReset() {
			super.onReset();

			// Ensure the loader is stopped
			onStopLoading();

			// At this point we can release the resources associated with 'apps'
			// if needed.
			if (mNhanCongChiTiets != null) {
				onReleaseResources(mNhanCongChiTiets);
				mNhanCongChiTiets = null;
			}
		}

		/**
		 * Helper function to take care of releasing resources associated
		 * with an actively loaded data set.
		 */
		protected void onReleaseResources(List<NhanCongChiTietModel> datas) {
			// For a simple List<> there is nothing to do.  For something
			// like a Cursor, we would close it here.
		}
	}
}
